<template>
  <div class="history-data">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="form" inline class="search-form">
        <el-form-item label="条码号">
          <el-input v-model="form.barCode" placeholder="请输入条码号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.userName" placeholder="请输入姓名" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="form.startTime"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="form.endTime"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="上传状态">
          <el-select 
            v-model="form.isUpload" 
            placeholder="请选择上传状态" 
            clearable 
            style="width: 200px;"
          >
            <el-option label="未上传" :value="0" />
            <el-option label="已上传" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" :icon="Search">🔍 搜索</el-button>
          <el-button @click="resetForm" :icon="Refresh">🔄 重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 主体内容区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">📋 测量记录列表</span>
          <div class="header-actions">
            <div class="record-stats">
              <el-tag type="info">共 {{ total }} 条记录</el-tag>
              <el-tag type="primary" v-if="selectedItems.length > 0">已选择 {{ selectedItems.length }} 条</el-tag>
            </div>
            <div class="action-buttons">
              <el-button 
                type="warning" 
                @click="smartUpload" 
                :loading="aiUploading"
              >
                {{ aiUploading ? '🤖 分析中...' : '🤖 智能上传' }}
              </el-button>
              <el-button 
                type="primary" 
                @click="batchUpload" 
                :disabled="selectedItems.length === 0 || uploading"
                :loading="uploading"
                v-if="selectedItems.length > 0"
                :icon="Upload"
              >
                {{ uploading ? '上传中...' : `📤 批量上传(${selectedItems.length})` }}
              </el-button>
              <el-button 
                type="danger" 
                @click="batchDelete" 
                :disabled="selectedItems.length === 0 || deleting"
                :loading="deleting"
                v-if="selectedItems.length > 0"
                :icon="Delete"
              >
                {{ deleting ? '删除中...' : `🗑️ 批量删除(${selectedItems.length})` }}
              </el-button>
            </div>
          </div>
        </div>
      </template>
      
      <!-- 血压颜色说明 -->
      <el-alert
        title="💡 血压状态颜色说明"
        type="info"
        :closable="false"
        class="color-legend"
      >
        <div class="legend-items">
          <div class="legend-item">
            <div class="legend-color high"></div>
            <span>血压偏高 (收缩压≥140 或 舒张压≥90)</span>
          </div>
          <div class="legend-item">
            <div class="legend-color normal"></div>
            <span>血压正常</span>
          </div>
          <div class="legend-item">
            <div class="legend-color low"></div>
            <span>血压偏低 (收缩压<90 或 舒张压<60)</span>
          </div>
        </div>
      </el-alert>
      
      <div class="table-container">
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading"
          @selection-change="handleSelectionChange"
          :height="tableHeight"
          class="custom-table"
        >
        <el-table-column type="selection" width="55" :selectable="isSelectable" />
        <el-table-column prop="barCode" label="条码号" width="120" show-overflow-tooltip />
        <el-table-column prop="userName" label="姓名" width="100" />
        <el-table-column label="收缩压" width="100" align="center">
          <template #default="{ row }">
            <div class="pressure-cell">
              <span class="pressure-value" :class="getBloodPressureClass(row)">
                {{ row.systolicPressure || '-' }}
              </span>
              <span class="pressure-unit">mmHg</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="舒张压" width="100" align="center">
          <template #default="{ row }">
            <div class="pressure-cell">
              <span class="pressure-value" :class="getBloodPressureClass(row)">
                {{ row.diastolicPressure || '-' }}
              </span>
              <span class="pressure-unit">mmHg</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="心率" width="80" align="center">
          <template #default="{ row }">
            <div class="pulse-cell">
              <span class="pulse-value">{{ row.pulse || '-' }}</span>
              <span class="pulse-unit">bpm</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="血压结果" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getBloodPressureTagType(row)" size="small">
              {{ getBloodPressureText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="measurementTime" label="测量时间" width="180" />
        <el-table-column prop="deviceName" label="设备名称" width="120">
          <template #default="{ row }">
            {{ row.deviceName || '默认设备' }}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作员" width="100" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.operator || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <div v-if="row.isUpload === 1" class="upload-status">
              <el-tag type="success" size="small">✅ 已上传</el-tag>
            </div>
            <div v-else-if="row.isUpload === 2" class="upload-status">
              <el-tag type="warning" size="small">⚠️ 上传失败</el-tag>
            </div>
            <el-button v-else type="primary" size="small" @click="upload(row)" :icon="Upload">
              📤 上传
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pageCurrent"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      </div>
    </el-card>

    <!-- AI智能上传弹窗 -->
    <el-dialog
      v-model="showAiModal"
      title="🤖 AI智能上传结果"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="ai-modal-content">
        <el-alert
          :title="`共检测到 ${aiResults.length} 条待上传记录`"
          type="info"
          :closable="false"
          class="result-info"
        />
        
        <div class="ai-results-list" v-if="aiResults.length > 0">
          <el-card 
            v-for="(item, index) in aiResults" 
            :key="item.id"
            class="ai-result-item"
            shadow="hover"
          >
            <div class="result-header">
              <span class="result-index">{{ index + 1 }}.</span>
              <span class="result-name">{{ item.userName || '未知' }}</span>
              <el-tag size="small" type="info">{{ item.barCode || '无条码' }}</el-tag>
            </div>
            <div class="result-data">
              <div class="data-group">
                <span class="data-label">血压：</span>
                <span class="data-value">{{ item.systolicPressure }}/{{ item.diastolicPressure }} mmHg</span>
              </div>
              <div class="data-group">
                <span class="data-label">心率：</span>
                <span class="data-value">{{ item.pulse }} bpm</span>
              </div>
              <div class="data-group">
                <span class="data-label">性别：</span>
                <span class="data-value">{{ item.gender || '未知' }}</span>
              </div>
            </div>
            <div class="result-time">
              <el-text type="info" size="small">{{ item.measurementTime }}</el-text>
            </div>
          </el-card>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAiModal">取消</el-button>
          <el-button type="primary" @click="confirmAiUpload" :loading="confirmUploading">
            {{ confirmUploading ? '上传中...' : '确定上传' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, Refresh, Upload, Delete } from '@element-plus/icons-vue'
import {
  queryListPage,
  batchUploadResults,
  getAiSubmitResult,
  aiSubmit,
  deleteBatchResults,
  getUserInfoByBarCode
} from '../api/business.js'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedItems = ref([])
const total = ref(0)
const pageSize = ref(10)
const pageCurrent = ref(1)
const uploading = ref(false)
const deleting = ref(false)

// 加载管理器
let loadingInstance = null
const showLoading = (text = '加载中...') => {
  if (loadingInstance) {
    loadingInstance.close()
  }
  loadingInstance = ElLoading.service({
    lock: true,
    text: text,
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

const hideLoading = () => {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

// 搜索表单
const form = reactive({
  barCode: '',
  userName: '',
  startTime: '',
  endTime: '',
  isUpload: undefined
})

// AI智能上传相关
const showAiModal = ref(false)
const aiResults = ref([])
const aiUploading = ref(false)
const confirmUploading = ref(false)

// 计算表格高度 - 动态计算可用高度
const tableHeight = computed(() => {
  // 动态计算表格高度，为分页器预留足够空间
  return 'calc(100vh - 420px)'
})

// 设置默认时间范围（当天）
const setDefaultTimeRange = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth()
  const date = now.getDate()
  
  const today = new Date(year, month, date)
  const formatDate = (date) => {
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
  }
  
  form.startTime = formatDate(today)
  form.endTime = formatDate(today)
}

// 获取当天时间范围
const getTodayTimeRange = () => {
  const now = new Date()
  const startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)
  const endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999)
  
  const formatDateTime = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  return {
    startTime: formatDateTime(startTime),
    endTime: formatDateTime(endTime)
  }
}

// 格式化用户自定义时间范围
const formatTimeRange = (startTime, endTime) => {
  let start, end
  
  if (startTime) {
    start = new Date(startTime + 'T00:00:00')
  }
  
  if (endTime) {
    end = new Date(endTime + 'T23:59:59')
  }
  
  if (!start && end) {
    start = new Date(end)
    start.setHours(0, 0, 0, 0)
  }
  if (!end && start) {
    end = new Date(start)
    end.setHours(23, 59, 59, 999)
  }
  
  if (start && end && start > end) {
    const temp = new Date(start)
    start = new Date(end.toDateString() + ' 00:00:00')
    end = new Date(temp.toDateString() + ' 23:59:59')
  }
  
  const formatDateTime = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  return {
    startTime: start ? formatDateTime(start) : '',
    endTime: end ? formatDateTime(end) : ''
  }
}

// 获取数据
const getData = async (pageCurrent, searchForm = {}, isLoadMore = false) => {
  loading.value = true
  
  try {
    let timeRange
    if (searchForm.startTime || searchForm.endTime) {
      timeRange = formatTimeRange(searchForm.startTime, searchForm.endTime)
    } else {
      timeRange = getTodayTimeRange()
    }
    
    const params = {
      pageNum: pageCurrent,
      pageSize: pageSize.value,
      startMeasurementTime: timeRange.startTime,
      endMeasurementTime: timeRange.endTime,
      ...searchForm
    }
    
    // 处理isUpload参数
    if (params.isUpload !== undefined) {
      params.isUpload = params.isUpload
    }
    
    delete params.startTime
    delete params.endTime
    
    const res = await queryListPage(params)
    console.info(res)
    
    if (res && res.success === true && res.content) {
      const newData = res.content.list || []
      
      // 为每条记录添加选中状态
      newData.forEach(item => {
        item.isSelected = false
      })
      
      total.value = res.content.total || 0
      tableData.value = newData
      
      ElMessage.success(`📋 成功获取${tableData.value.length}条记录`)
    } else {
      throw new Error(res?.message || '数据格式错误')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error(error.data?.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const search = () => {
  selectedItems.value = []
  pageCurrent.value = 1
  getData(1, form, false)
}

// 重置表单
const resetForm = () => {
  form.barCode = ''
  form.userName = ''
  form.startTime = ''
  form.endTime = ''
  form.isUpload = undefined
  
  setDefaultTimeRange()
  
  selectedItems.value = []
  pageCurrent.value = 1
  getData(1, {}, false)
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  getData(pageCurrent.value, form, false)
}

const handleCurrentChange = (page) => {
  pageCurrent.value = page
  getData(page, form, false)
}

// 表格选择处理
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

const isSelectable = (row) => {
  return row.isUpload === 0 // 只有未上传的记录可以选择
}

// 血压状态判断
const getBloodPressureClass = (item) => {
  if (!item || !item.systolicPressure || !item.diastolicPressure) {
    return 'normal'
  }
  
  const systolic = Number(item.systolicPressure)
  const diastolic = Number(item.diastolicPressure)
  
  if (systolic >= 140 || diastolic >= 90) {
    return 'high'
  }
  
  if (systolic < 90 || diastolic < 60) {
    return 'low'
  }
  
  return 'normal'
}

const getBloodPressureText = (item) => {
  if (!item || !item.systolicPressure || !item.diastolicPressure) {
    return '-'
  }
  
  const systolic = Number(item.systolicPressure)
  const diastolic = Number(item.diastolicPressure)
  
  if (systolic >= 140 || diastolic >= 90) {
    return '血压偏高'
  }
  
  if (systolic < 90 || diastolic < 60) {
    return '血压偏低'
  }
  
  return '血压正常'
}

const getBloodPressureTagType = (item) => {
  const classType = getBloodPressureClass(item)
  const typeMap = {
    high: 'danger',
    low: 'warning',
    normal: 'success'
  }
  return typeMap[classType] || 'info'
}

// 单个上传
const upload = async (item) => {
  try {
    if (!item.id) {
      throw new Error('记录没有有效的ID')
    }
    
    const shouldContinueUpload = await validateUserBeforeUpload(item.barCode)
    if (!shouldContinueUpload) {
      return
    }
    
    showLoading('上传中...')
    
    const res = await batchUploadResults([item.id])
    
    hideLoading()
    
    // 检查接口返回的success字段
    if (res && res.success === true) {
      item.isUpload = 1
      ElMessage.success('✅ 上传成功')
      
      setTimeout(() => {
        search()
      }, 500)
    } else {
      // 接口返回失败
      throw new Error(res?.message || '上传失败')
    }
  } catch (error) {
    hideLoading()
    console.error('单个上传失败:', error)
    ElMessage.error('❌ ' + (error.message || error.data?.message || '上传失败'))
  }
}

// 批量上传
const batchUpload = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要上传的记录')
    return
  }

  const shouldContinueUpload = await validateBatchUsersBeforeUpload(selectedItems.value)
  if (!shouldContinueUpload) {
    return
  }

  uploading.value = true
  showLoading('批量上传中...')

  try {
    const ids = selectedItems.value.map(item => item.id).filter(id => id !== undefined)
    
    if (ids.length === 0) {
      throw new Error('选中的记录没有有效的ID')
    }

    const res = await batchUploadResults(ids)
    
    hideLoading()
    
    // 检查接口返回的success字段
    if (res && res.success === true) {
      ElMessage.success(`✅ 成功上传`)
      
      setTimeout(() => {
        search()
      }, 500)
      
      selectedItems.value.forEach(item => {
        item.isUpload = 1
        item.isSelected = false
      })
      
      selectedItems.value = []
    } else {
      // 接口返回失败
      throw new Error(res?.message || '批量上传失败')
    }
    
  } catch (error) {
    hideLoading()
    console.error('批量上传失败:', error)
    ElMessage.error('❌ ' + (error.message || error.data?.message || '批量上传失败'))
  } finally {
    uploading.value = false
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 条测量记录吗？删除后无法恢复。`, '确认批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    deleting.value = true
    showLoading('批量删除中...')

    const ids = selectedItems.value.map(item => item.id).filter(id => id !== undefined)
    
    if (ids.length === 0) {
      throw new Error('选中的记录没有有效的ID')
    }

    await deleteBatchResults(ids)
    
    hideLoading()
    ElMessage.success(`✅ 成功删除 ${ids.length} 条记录`)

    selectedItems.value = []
    
    setTimeout(() => {
      search()
    }, 500)
    
  } catch (error) {
    if (error !== 'cancel') {
      hideLoading()
      ElMessage.error('❌ ' + (error.data?.message || '批量删除失败'))
    }
  } finally {
    deleting.value = false
  }
}

// AI智能上传
const smartUpload = async () => {
  aiUploading.value = true
  
  try {
    showLoading('AI分析中...')

    const res = await getAiSubmitResult()

    if (res && res.success) {
      aiResults.value = res.content
      
      if (aiResults.value != null && aiResults.value.length > 0) {
        showAiModal.value = true
        hideLoading()
      } else {
        hideLoading()
        ElMessage.info('🤖 AI未检测到待上传记录')
      }
    } else {
      throw new Error(res?.message || 'AI分析失败')
    }
  } catch (error) {
    hideLoading()
    
    let errorMessage = 'AI智能分析失败'
    if (error.data && error.data.message) {
      errorMessage = error.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    try {
      await ElMessageBox.confirm(errorMessage + '\n\n请检查网络连接或联系技术支持', '🤖 智能分析失败', {
        confirmButtonText: '重试分析',
        cancelButtonText: '关闭',
        type: 'error'
      })
      
      setTimeout(() => {
        smartUpload()
      }, 300)
    } catch {
      // 用户取消
    }
  } finally {
    aiUploading.value = false
  }
}

// 关闭AI弹窗
const closeAiModal = () => {
  showAiModal.value = false
  aiResults.value = []
}

// 确认AI上传
const confirmAiUpload = async () => {
  const shouldContinueUpload = await validateAiUsersBeforeUpload(aiResults.value)
  if (!shouldContinueUpload) {
    return
  }

  confirmUploading.value = true
  
  try {
    showLoading('正在上传...')

    const res = await aiSubmit()

    if (res && res.success) {
      hideLoading()
      
      closeAiModal()
      
      setTimeout(() => {
        ElMessage.success(`✅ 成功上传`)
      }, 300)

      setTimeout(() => {
        search()
      }, 1500)
    } else {
      throw new Error(res?.message || '上传失败')
    }
  } catch (error) {
    hideLoading()
    
    let errorMessage = '数据上传失败'
    if (error.data && error.data.message) {
      errorMessage = error.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    try {
      await ElMessageBox.confirm(errorMessage, '❌ 上传失败', {
        confirmButtonText: '重试上传',
        cancelButtonText: '关闭',
        type: 'error'
      })
      
      setTimeout(() => {
        confirmAiUpload()
      }, 300)
    } catch {
      // 用户取消
    }
  } finally {
    confirmUploading.value = false
  }
}

// 用户验证函数
const validateUserBeforeUpload = async (barCode) => {
  if (!barCode || !barCode.trim()) {
    return true
  }

  try {
    showLoading('验证用户信息...')

    const res = await getUserInfoByBarCode(barCode.trim())

    hideLoading()

    if (res && res.content) {
      return true
    } else {
      try {
        await ElMessageBox.confirm(`患者信息不存在（条码号：${barCode}），是否继续上传？`, '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        })
        return true
      } catch {
        return false
      }
    }
  } catch (error) {
    hideLoading()
    
    let errorMessage = '患者信息不存在'
    if (error.data && error.data.message) {
      errorMessage = error.data.message
    } else if (error.message) {
      errorMessage = error.message
    }

    try {
      await ElMessageBox.confirm(`${errorMessage}（条码号：${barCode}），是否继续上传？`, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
      return true
    } catch {
      return false
    }
  }
}

const validateBatchUsersBeforeUpload = async (selectedItems) => {
  if (!selectedItems || selectedItems.length === 0) {
    return true
  }

  const barCodes = [...new Set(selectedItems.map(item => item.barCode).filter(code => code && code.trim()))]
  
  if (barCodes.length === 0) {
    return true
  }

  try {
    showLoading('批量验证用户信息...')

    const validationPromises = barCodes.map(async (barCode) => {
      try {
        const res = await getUserInfoByBarCode(barCode.trim())
        return {
          barCode: barCode,
          exists: !!(res && res.content),
          error: null
        }
      } catch (error) {
        return {
          barCode: barCode,
          exists: false,
          error: error.data?.message || error.message || '查询失败'
        }
      }
    })

    const validationResults = await Promise.all(validationPromises)
    hideLoading()

    const notFoundUsers = validationResults.filter(result => !result.exists)
    
    if (notFoundUsers.length === 0) {
      return true
    }

    const notFoundBarCodes = notFoundUsers.map(user => user.barCode).join('、')
    const content = `以下患者信息不存在：\n${notFoundBarCodes}\n\n是否继续批量上传？`

    try {
      await ElMessageBox.confirm(content, '批量验证结果', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
      return true
    } catch {
      return false
    }

  } catch (error) {
    hideLoading()
    
    let errorMessage = '批量验证用户信息失败'
    if (error.message) {
      errorMessage = error.message
    }

    try {
      await ElMessageBox.confirm(`${errorMessage}，是否继续批量上传？`, '验证失败', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
      return true
    } catch {
      return false
    }
  }
}

const validateAiUsersBeforeUpload = async (aiResults) => {
  if (!aiResults || aiResults.length === 0) {
    return true
  }

  const barCodes = [...new Set(aiResults.map(item => item.barCode).filter(code => code && code.trim()))]
  
  if (barCodes.length === 0) {
    return true
  }

  try {
    showLoading('AI验证用户信息...')

    const validationPromises = barCodes.map(async (barCode) => {
      try {
        const res = await getUserInfoByBarCode(barCode.trim())
        return {
          barCode: barCode,
          exists: !!(res && res.content),
          error: null
        }
      } catch (error) {
        return {
          barCode: barCode,
          exists: false,
          error: error.data?.message || error.message || '查询失败'
        }
      }
    })

    const validationResults = await Promise.all(validationPromises)
    hideLoading()

    const notFoundUsers = validationResults.filter(result => !result.exists)
    
    if (notFoundUsers.length === 0) {
      return true
    }

    const notFoundBarCodes = notFoundUsers.map(user => user.barCode).join('、')
    const content = `以下患者信息不存在：\n${notFoundBarCodes}\n\n是否继续AI智能上传？`

    try {
      await ElMessageBox.confirm(content, 'AI验证结果', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
      return true
    } catch {
      return false
    }

  } catch (error) {
    hideLoading()
    
    let errorMessage = 'AI验证用户信息失败'
    if (error.message) {
      errorMessage = error.message
    }

    try {
      await ElMessageBox.confirm(`${errorMessage}，是否继续AI智能上传？`, 'AI验证失败', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
      return true
    } catch {
      return false
    }
  }
}

// 组件挂载时初始化
onMounted(() => {
  setDefaultTimeRange()
  getData(1, form, false)
})
</script><style 
scoped>
.history-data {
  background: #f5f7fa;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
  flex-shrink: 0;
}

.page-header h2 {
  margin: 0;
  color: #1e40af;
  font-size: 24px;
  font-weight: 700;
}

.search-card {
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.search-form {
  padding: 0px 0;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  padding-bottom: 70px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 700;
  color: #1e40af;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.record-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.color-legend {
  margin-bottom: 16px;
  border-radius: 8px;
}

.legend-items {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  align-items: center;
  margin-top: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  flex-shrink: 0;
}

.legend-color.high {
  background: #f56565;
}

.legend-color.normal {
  background: #48bb78;
}

.legend-color.low {
  background: #4299e1;
}

.pressure-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.pressure-value {
  font-size: 14px;
  font-weight: 700;
  line-height: 1.2;
}

.pressure-value.high {
  color: #e53e3e;
}

.pressure-value.normal {
  color: #38a169;
}

.pressure-value.low {
  color: #3182ce;
}

.pressure-unit {
  font-size: 10px;
  color: #718096;
}

.pulse-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.pulse-value {
  font-size: 14px;
  font-weight: 700;
  color: #e53e3e;
  line-height: 1.2;
}

.pulse-unit {
  font-size: 10px;
  color: #718096;
}

.upload-status {
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-container {
  flex: 1;
  overflow: hidden;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.custom-table {
  width: 100%;
  flex: 1;
}

.pagination {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background: #ffffff;
  border-top: 1px solid #e4e7ed;
  z-index: 10;
}
/* 表格滚动条样式 */
:deep(.el-table) {
  height: 100% !important;
}

:deep(.el-table__body-wrapper) {
  /* 只在需要时显示滚动条 */
  overflow-y: auto !important;
  overflow-x: hidden !important;
  max-height: calc(100vh - 470px) !important;
  /* 为底部分页器预留更多空间，避免遮挡 */
  padding-bottom: 10px !important;
}

/* 滚动条样式优化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
  transition: background 0.3s ease;
  min-height: 20px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-corner {
  background: #f5f5f5;
}

/* 表格横向铺满 */
:deep(.el-table) {
  width: 100% !important;
  min-width: 100% !important;
}

:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__footer-wrapper) {
  width: 100% !important;
}

/* 确保表格内容不会超出容器 */
:deep(.el-table__header),
:deep(.el-table__body) {
  width: 100% !important;
  table-layout: fixed;
}

/* 表格单元格内容溢出处理 */
:deep(.el-table .cell) {
  word-break: break-word;
  word-wrap: break-word;
  white-space: normal;
  line-height: 1.4;
}

/* 确保最后一行数据不被遮挡 */
:deep(.el-table__body tr:last-child td) {
  border-bottom: 1px solid #ebeef5;
}

/* AI弹窗样式 */
.ai-modal-content {
  max-height: 60vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.result-info {
  margin-bottom: 16px;
}

.ai-results-list {
  flex: 1;
  overflow-y: auto;
  max-height: 400px;
  padding: 8px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: #f7fafc;
}

.ai-result-item {
  margin-bottom: 12px;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.ai-result-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.ai-result-item:last-child {
  margin-bottom: 0;
}

.result-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e2e8f0;
}

.result-index {
  font-size: 14px;
  font-weight: 700;
  color: #805ad5;
  min-width: 20px;
}

.result-name {
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
  flex: 1;
}

.result-data {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.data-group {
  display: flex;
  align-items: center;
  gap: 4px;
}

.data-label {
  font-size: 13px;
  color: #718096;
  font-weight: 500;
}

.data-value {
  font-size: 14px;
  color: #2d3748;
  font-weight: 600;
}

.result-time {
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-data {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }
  
  .legend-items {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .result-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .result-data {
    flex-direction: column;
    gap: 8px;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
  
  .search-form .el-input,
  .search-form .el-date-picker {
    width: 100% !important;
  }
}
</style>